import nodemailer from "nodemailer";
import fs from "fs";

export class EmailTools {
    /**
     * 初始化 EmailTools
     * @param {Object} config 邮箱配置
     * @param {string} config.smtp_server SMTP 服务器地址
     * @param {number} config.port 端口号（默认 465）
     * @param {string} config.sender_email 发件人邮箱
     * @param {string} config.auth_code SMTP 授权码（非邮箱登录密码）
     */
    constructor({
                    smtp_server = "smtp.qq.com",
                    port = 465,
                    sender_email = "570311614@qq.com",
                    auth_code = "epbgwpvhklsybegj",
                } = {}) {
        this.smtp_server = smtp_server;
        this.port = port;
        this.sender_email = sender_email;
        this.auth_code = auth_code;

        // 创建SMTP连接池
        this.transporter = nodemailer.createTransport({
            host: this.smtp_server,
            port: this.port,
            secure: true, // true表示使用SSL
            auth: {
                user: this.sender_email,
                pass: this.auth_code,
            },
        });
    }

    /**
     * 发送邮件
     * @param {string[]} toEmails 收件人邮箱数组
     * @param {string} subject 邮件主题
     * @param {string} body 邮件内容
     * @param {"plain" | "html"} bodyType 内容格式
     * @param {string[]} [attachments] 附件路径列表
     * @returns {Promise<boolean>} 是否发送成功
     */
    // ✅ 支持对象调用方式 { to_emails, subject, body, ... }
    async sendEmail({ to_emails = [], subject, body, bodyType = "plain", attachments = [] }) {
        try {
            const toList = Array.isArray(to_emails) ? to_emails.join(", ") : to_emails;
            const mailOptions = {
                from: this.sender_email,
                to: toList,
                subject,
                [bodyType === "html" ? "html" : "text"]: body,
                attachments: attachments.map((path) => ({
                    filename: path.split("/").pop(),
                    path,
                })),
            };

            await this.transporter.sendMail(mailOptions);
            console.log("✅ 邮件发送成功！");
            return true;
        } catch (err) {
            console.error("❌ 邮件发送失败:", err.message);
            return false;
        }
    }

}
